package cn.amarone.scaffold.config.global;

import cn.amarone.scaffold.config.business.common.BaseRsp;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Amarone
 * @version 1.0
 * @description:
 * @date 2023/8/2 10:43
 */
@RestControllerAdvice
public class BusinessExceptionHandler {
    public static final String MISSING_MSG = "Required request body is missing";

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public BaseRsp exceptionHandle(HttpMessageNotReadableException e) {
        if (e.getMessage().startsWith(MISSING_MSG)) {
            return BaseRsp.error("错误的请求方式，请调整Content-Type！");
        } else {
            return BaseRsp.error(e.getMessage());
        }
    }

    @ExceptionHandler(HttpMessageConversionException.class)
    public BaseRsp exceptionHandle(HttpMessageConversionException e) {
        return BaseRsp.error("参数转化异常！");
    }

    @ExceptionHandler(ClassCastException.class)
    public BaseRsp exceptionHandle(ClassCastException e) {
        return BaseRsp.error("参数转化异常！");
    }

    @ExceptionHandler(Exception.class)
    public BaseRsp exceptionHandle(Exception e) {
        e.printStackTrace();
        return BaseRsp.error(e.getMessage());
    }
}
